package com.rp.demo.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.rp.demo.commons.MessageHelper;
import com.rp.demo.commons.ResponseCode;
import com.rp.demo.commons.ServerResponse;
import com.rp.demo.config.RabbitConfig;
import com.rp.demo.dto.Mail;
import com.rp.demo.entity.MsgLog;
import com.rp.demo.mapper.MsgLogMapper;
import com.rp.demo.service.TestService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 发送消息业务层
 */
@Service
@Slf4j
public class TestServiceImpl implements TestService {

    @Autowired
    private MsgLogMapper msgLogMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public ServerResponse send(Mail mail) {
        String msgId = IdUtil.randomUUID();
        mail.setMsgId(msgId);

        MsgLog msgLog = new MsgLog(msgId, mail, RabbitConfig.MAIL_EXCHANGE_NAME, RabbitConfig.MAIL_ROUTING_KEY_NAME);
        msgLogMapper.insert(msgLog);// 消息入库

        log.info("============================{1}=================================");
        log.info("======>{}", JSONUtil.toJsonStr(msgLog));

        CorrelationData correlationData = new CorrelationData(msgId);
        rabbitTemplate.convertAndSend(
                RabbitConfig.MAIL_EXCHANGE_NAME,
                RabbitConfig.MAIL_ROUTING_KEY_NAME,
                MessageHelper.objToMsg(mail),
                correlationData);// 发送消息

        return ServerResponse.success(ResponseCode.MAIL_SEND_SUCCESS.getMsg());
    }

}